package com.work.cos.domain.vo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *类功能说明：内存缓存数据
 */
public class ComMemoryCacheContext
{
	/**
     * 默认构造器
     */
    private ComMemoryCacheContext() {
    }

    /**
     * @see ReentrantReadWriteLock
     */
    private static final ReentrantReadWriteLock READ_WRITE_LOCK = 
      new ReentrantReadWriteLock();

    /**
     * 读锁
     */
    private static final Lock READ_LOCK = READ_WRITE_LOCK.readLock();

    /**
     * 写锁
     */
    private static final Lock WRITE_LOCK = READ_WRITE_LOCK.writeLock();

    /**
     * 缓存用HashMap，并保证线程同步的
     */
    private static final Map<String, Object> CACHE_MAP;

    static {
      CACHE_MAP = new HashMap<String, Object>();
    }

    /**
     * 添加对象至缓存
     * 
     * @param key 键
     * @param obj 值
     */
    public static void putObject2Memory(String key, Object obj) {
      WRITE_LOCK.lock();
      try {
        CACHE_MAP.put(key, obj);
      } finally {
        WRITE_LOCK.unlock();
      }
    }
    
    /**
     * 清除缓存
     * 
     * @param key 键
     */
    public static void removeObject2Memory(String key) {
      WRITE_LOCK.lock();
      try {
        CACHE_MAP.remove(key);
      } finally {
        WRITE_LOCK.unlock();
      }
    }

    /**
     * 获取缓存对象
     * 
     * @param key 键
     * @return 值
     */
	public static Object getObjectFromMemory(String key)
	{
		READ_LOCK.lock();
		try
		{
			return CACHE_MAP.get(key);
		}
		finally
		{
			READ_LOCK.unlock();
		}
	}
}
